package com.wkh.datastructure.BinaryTree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 寻找最大深度
 */
public class MaximumDepth {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,
                new TreeNode(2,null,null),
                new TreeNode(3,
                        null,
                        new TreeNode(4,null,null)));
//        TreeNode root = new TreeNode(1,null,null);
        int count = maximumDepth3(root);
        System.out.println(count);
    }

    private static int maximumDepth1(TreeNode root) {
        if (root == null){
            return 0;
        }
        if (root.left == null && root.right == null){
            return 1;
        }
        int d1 = maximumDepth1(root.left);
        int d2 = maximumDepth1(root.right);
        return Integer.max(d1,d2)+1;
    }

    //利用非递归方法获取最大深度
    public static int maximumDepth2(TreeNode root){
        //记录深度
        int max = 0;
        TreeNode cur = root;
        //表示最近弹栈的元素
        TreeNode pop = null;
        //存储元素的栈
        LinkedList<TreeNode> stack = new LinkedList<>();
        while (cur != null || !stack.isEmpty()){
            if (cur != null){
                stack.push(cur);
                int size = stack.size();
                if (size>max){
                    max = size;
                }
                cur = cur.left;
            }else {
                TreeNode peek = stack.peek();
                if (peek.right == null || peek.right == pop){
                    pop = stack.pop();
                }else {
                    cur = peek.right;
                }
            }
        }
        return max;
    }

    //利用层序遍历方法获取最大深度
    public static int maximumDepth3(TreeNode root){
        if (root == null){
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left!=null){
                    queue.offer(poll.left);
                }
                if (poll.right!=null){
                    queue.offer(poll.right);
                }
            }
            depth++;
        }
       return depth;
    }
}
